<template>
  <div class="commission-container">
    <div class="query-container">
      <el-form :inline="true" :model="queryParams" class="query-form">
        <el-form-item label="分类名称">
          <el-input v-model="queryParams.name" placeholder="请输入分类名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <div class="table-header">
        <el-button type="primary" @click="handleAdd">新增分类</el-button>
        <el-button type="danger" :disabled="!selectedCommissions.length" @click="handleBatchDelete">批量删除</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="commissionList"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column prop="name" label="分类名称" />
        <el-table-column prop="rate" label="佣金比例" width="180">
          <template #default="{ row }">
            {{ row.rate }}%
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="total > 0"
        :current-page="queryParams.page"
        :page-size="queryParams.limit"
        :total="total"
        layout="total, prev, pager, next, jumper"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="500px"
      @close="resetForm"
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="佣金比例" prop="rate">
          <el-input-number 
            v-model="form.rate" 
            :min="0" 
            :max="100" 
            :precision="2" 
            :step="0.1"
            placeholder="请输入佣金比例"
          />
          <span class="rate-unit">%</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/* eslint-disable no-undef */
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  getCommissionCategories, 
  createCommissionCategory, 
  updateCommissionCategory, 
  deleteCommissionCategory,
  batchDeleteCommissionCategories
} from '@/api/commissionCategories';

defineOptions({
  name: 'CommissionListPage'
});

// 查询参数
const queryParams = reactive({
  name: '',
  page: 1,
  limit: 10
});

// 分类列表数据
const commissionList = ref([]);
const total = ref(0);
const loading = ref(false);
const selectedCommissions = ref([]);

// 表单数据
const dialogVisible = ref(false);
const dialogTitle = ref('');
const submitLoading = ref(false);
const formRef = ref(null);
const form = reactive({
  id: null,
  name: '',
  rate: 0
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  rate: [
    { required: true, message: '请输入佣金比例', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '比例在 0 到 100 之间', trigger: 'blur' }
  ]
};

// 查询分类列表
const loadCommissionList = async () => {
  loading.value = true;
  try {
    const response = await getCommissionCategories(queryParams);
    commissionList.value = response.results;
    total.value = response.count;
  } catch (error) {
    console.error('获取佣金分类列表失败:', error);
    ElMessage.error('获取佣金分类列表失败');
  } finally {
    loading.value = false;
  }
};

// 查询按钮事件
const handleQuery = () => {
  queryParams.page = 1;
  loadCommissionList();
};

// 重置查询
const resetQuery = () => {
  queryParams.name = '';
  handleQuery();
};

// 页码变更
const handlePageChange = (page) => {
  queryParams.page = page;
  loadCommissionList();
};

// 选择变更
const handleSelectionChange = (selection) => {
  selectedCommissions.value = selection;
};

// 添加分类
const handleAdd = () => {
  dialogTitle.value = '添加佣金分类';
  dialogVisible.value = true;
  resetForm();
};

// 编辑分类
const handleEdit = (row) => {
  dialogTitle.value = '编辑佣金分类';
  form.id = row.id;
  form.name = row.name;
  form.rate = row.rate;
  dialogVisible.value = true;
};

// 删除分类
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除佣金分类 "${row.name}" 吗?`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await deleteCommissionCategory(row.id);
      ElMessage.success('删除成功');
      loadCommissionList();
    } catch (error) {
      console.error('删除佣金分类失败:', error);
      ElMessage.error('删除佣金分类失败');
    }
  }).catch(() => {});
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedCommissions.value.length === 0) {
    ElMessage.warning('请选择要删除的项');
    return;
  }

  const names = selectedCommissions.value.map(item => item.name).join('、');
  const ids = selectedCommissions.value.map(item => item.id);

  ElMessageBox.confirm(
    `确定要删除以下佣金分类吗?\n${names}`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await batchDeleteCommissionCategories(ids);
      ElMessage.success('批量删除成功');
      loadCommissionList();
    } catch (error) {
      console.error('批量删除佣金分类失败:', error);
      ElMessage.error('批量删除佣金分类失败');
    }
  }).catch(() => {});
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.id = null;
  form.name = '';
  form.rate = 0;
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true;
      try {
        if (form.id) {
          // 更新
          await updateCommissionCategory(form.id, {
            name: form.name,
            rate: form.rate
          });
          ElMessage.success('更新成功');
        } else {
          // 新增
          await createCommissionCategory({
            name: form.name,
            rate: form.rate
          });
          ElMessage.success('添加成功');
        }
        dialogVisible.value = false;
        loadCommissionList();
      } catch (error) {
        console.error('保存佣金分类失败:', error);
        ElMessage.error('保存佣金分类失败');
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

// 页面加载时获取数据
onMounted(() => {
  loadCommissionList();
});
</script>

<style scoped>
.commission-container {
  padding: 20px;
}

.query-container {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 18px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-container {
  background-color: #fff;
  padding: 18px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  margin-bottom: 18px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.rate-unit {
  margin-left: 8px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 